// WebSocket 封装类，默认加载就连接，支持发送和关闭
// 用法示例：
// const ws = MyWebSocket.getInstance();
// ws.send('hello');
// ws.close();

import feedback from "./feeback";
import { LoadingOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
import { h } from 'vue';
import { useUserStore } from '@/utils/stores/modules/user';
const key = 'websocket'



class MyWebSocket {
    private static instance: MyWebSocket;
    private socket: WebSocket | null = null;
    private url: string;
    public readyState: number = 0;
    private userStore = useUserStore();
    private constructor() {
        // 从环境变量获取 VITE_BASE_URL，并将 http 替换为 ws
        const baseUrl = import.meta.env.VITE_BASE_URL;
        this.url = baseUrl.replace('http', 'ws') + '/ws';
        // this.url = 'ws://192.168.1.67:7788/';
        if (import.meta.env.VITE_WEBSOCKET === 'true' || import.meta.env.VITE_WEBSOCKET === true) {
            setTimeout(() => {
                this.connect();
            }, 1000);
        }

    }

    public static getInstance(): MyWebSocket {
        if (!MyWebSocket.instance) {
            MyWebSocket.instance = new MyWebSocket();
        }
        return MyWebSocket.instance;
    }

    private connect() {
        this.socket = new window.WebSocket(this.url);

        this.readyState = this.socket.readyState;
        feedback.openNotification({
            message: 'WebSocket',
            description: '正在连接WebSocket...',
            key: key,
            duration: 0,
            icon: h(LoadingOutlined, { style: { color: '#1890ff' } }),
        });
        this.socket.onopen = () => {
            this.readyState = this.socket?.readyState ?? 0;
            console.log('WebSocket 连接成功');
            feedback.openNotification({
                message: 'WebSocket',
                description: 'WebSocket 连接成功',
                key: key,
                duration: 3,
                icon: h(CheckCircleOutlined, { style: { color: 'green' } }),
            });

            // 发送登录信息
            this.send({ message: 'login', type: 'login' });
        }
        this.socket.onmessage = (event) => {
            this.readyState = this.socket.readyState ?? 0;
            const data = JSON.parse(event.data);
            console.log('WebSocket 收到消息', data);

            for (const item of data.data) {
                switch (item.type) {
                    case 'Notification':
                        feedback.systemNotification({
                            message: '系统消息',
                            description: item.message,
                            duration: 3,
                            icon: h(CheckCircleOutlined, { style: { color: 'green' } }),
                        });
                        break;
                }
            }
            console.log('WebSocket 收到消息', event.data);
        }

        this.socket.onerror = (event) => {
            this.readyState = this.socket?.readyState ?? 0;
            console.log('WebSocket 连接失败', event);
            feedback.openNotification({
                message: 'WebSocket',
                description: 'WebSocket 连接失败',
                key: key,
                duration: 3,
                icon: h(CloseCircleOutlined, { style: { color: 'red' } }),
            });
        }

        this.socket.onclose = () => {
            this.readyState = this.socket?.readyState ?? 0;
            console.log('WebSocket 连接关闭');
            feedback.openNotification({
                message: 'WebSocket',
                description: 'WebSocket 连接关闭',
                key: key,
                duration: 3,
                icon: h(CloseCircleOutlined, { style: { color: 'red' } }),
            });
            setTimeout(() => {
                this.connect();
            }, 1000);
        }
    }

    public send(config: { message: string, type: string, roomId?: string }) {
        if (this.socket && this.socket.readyState === window.WebSocket.OPEN) {

            const data = {
                ...config,
                timestamp: Date.now(),
                userId: this.userStore.userInfo.id,
                username: this.userStore.userInfo.username,
                token: this.userStore.userInfo.token,
                event: 'admin',
            }
            this.socket.send(JSON.stringify(data));
        } else {
            throw new Error('WebSocket 未连接');
        }
    }

    public isConnected(): boolean {
        return this.socket?.readyState === window.WebSocket.OPEN;
    }

    public close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default MyWebSocket;